package org.dromara.shopping.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.mybatis.core.page.PageUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.shopping.service.IBdProvinceService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.shopping.domain.Organ;
import org.dromara.shopping.service.IOrganService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 易货机构
 *
 * @author Mr.Zhou
 * @date 2025-01-17
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/shopping/organ")
public class OrganController extends BaseController {

    private final IOrganService organService;
    private final IBdProvinceService bdProvinceService;

    /**
     * 查询易货机构列表
     */
    @SaCheckPermission("shopping:organ:list")
    @GetMapping("/list")
    public TableDataInfo<Organ> list(Organ organ, PageQuery pageQuery) {
        QueryWrapper<Organ> qw = new QueryWrapper<>();
        LoginUser loginUser = LoginHelper.getLoginUser();
        if ("organ".equals(loginUser.getRoleKey())){ // 机构角色
            qw.eq("id", loginUser.getOrganId());
        }

        TableDataInfo<Organ> td = PageUtils.buildDataInfo(organService.page(PageUtils.buildPage(),qw));
        List<Organ> list = td.getRows();
        for (Organ organ1 : list){
            organ1.setAreaName(bdProvinceService.getAreaNameByAreaId(organ1.getProvId(), organ1.getCityId(), 0));
        }
        return td;
    }

    /**
     * 机构列表(不分页，下拉框使用)
     */
    @GetMapping("/noPage/list")
    public R<List<Organ>> noPageList(Organ robotOrgan) {
        QueryWrapper<Organ> qw = new QueryWrapper<>();
        LoginUser loginUser = LoginHelper.getLoginUser();
        if ("organ".equals(loginUser.getRoleKey())){ // 机构角色
            qw.eq("id", loginUser.getOrganId());
        }
        List<Organ> list = organService.list(qw);
        return R.ok(list);
    }


    /**
     * 导出易货机构列表
     */
    @SaCheckPermission("shopping:organ:export")
    @Log(title = "易货机构", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(Organ organ, HttpServletResponse response) {
        List<Organ> list = organService.list();
        ExcelUtil.exportExcel(list, "易货机构", Organ.class, response);
    }

    /**
     * 获取易货机构详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("shopping:organ:query")
    @GetMapping("/{id}")
    public R<Organ> getInfo(@NotNull(message = "主键不能为空") @PathVariable Integer id) {
        Organ organ = organService.getById(id);
        if(organ!= null){
            if(organ.getProvId() != null){
                String[] areas = { organ.getProvId() + ""};
                organ.setProvinceArray(areas);
            }

            if(organ.getProvId() != null && organ.getCityId() != null){
                String[] areas = { organ.getProvId() + "", organ.getCityId() + ""};
                organ.setProvinceArray(areas);
            }
        }
        return R.ok(organ);
    }

    /**
     * 新增易货机构
     */
    @SaCheckPermission("shopping:organ:add")
    @Log(title = "易货机构", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody Organ organ) {
        if(organ.getProvinceArray() !=null && organ.getProvinceArray().length >= 2){
            organ.setProvId(Integer.parseInt(organ.getProvinceArray()[0]));
            organ.setCityId(Integer.parseInt(organ.getProvinceArray()[1]));
        }
        return toAjax(organService.save(organ));
    }

    /**
     * 修改易货机构
     */
    @SaCheckPermission("shopping:organ:edit")
    @Log(title = "易货机构", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody Organ organ) {
        if(organ.getProvinceArray() != null && organ.getProvinceArray().length >= 2){
            organ.setProvId(Integer.parseInt(organ.getProvinceArray()[0]));
            organ.setCityId(Integer.parseInt(organ.getProvinceArray()[1]));
        }
        return toAjax(organService.updateById(organ));
    }

    /**
     * 删除易货机构
     *
     * @param ids 主键串
     */
    @SaCheckPermission("shopping:organ:remove")
    @Log(title = "易货机构", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
        return toAjax(organService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
